package com.itzhanghada.rebitmq.mq;

import com.itzhanghada.rebitmq.domin.vo.TransactionRecord;
import com.itzhanghada.rebitmq.enums.TransactionStatus;
import com.itzhanghada.rebitmq.redis.RedisStorageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
public class MessageSender {
    private static final Logger logger = LoggerFactory.getLogger(MessageSender.class);
    
    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    @Autowired
    private RedisStorageService storageService;
    
    public void sendMessage(TransactionRecord record) {
        try {
            // 设置消息头
            MessageProperties properties = new MessageProperties();
            properties.setHeader("TX_ID", record.getTxId());
            properties.setHeader("RETRY_COUNT", String.valueOf(record.getRetryCount()));
            properties.setHeader("CREATE_TIME", String.valueOf(record.getCreateTime()));
            properties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
            
            // 创建消息
            Message message = new Message(record.getBody().getBytes(StandardCharsets.UTF_8), properties);
            
            // 发送消息
            rabbitTemplate.send(record.getExchange(), record.getRoutingKey(), message);
            
            // 更新状态为SENT
            storageService.updateTransactionStatus(record.getTxId(), TransactionStatus.SENT);
            
            logger.info("Message sent successfully, txId: {}", record.getTxId());
        } catch (Exception e) {
            logger.error("Failed to send message, txId: {}", record.getTxId(), e);
            
            // 发送失败，更新状态为RETRYING
            storageService.updateTransactionStatus(record.getTxId(), TransactionStatus.RETRYING);
            
            // 增加重试次数
            incrementRetryCount(record.getTxId());
        }
    }
    
    private void incrementRetryCount(String txId) {
        // 从Redis获取记录，增加重试次数，再保存回去
        TransactionRecord record = storageService.getTransactionRecord(txId);
        if (record != null) {
            record.setRetryCount(record.getRetryCount() + 1);
            record.setUpdateTime(System.currentTimeMillis());
            storageService.saveTransactionRecord(record);
        }
    }
}